use core::ffi::c_void;
use core::ptr::null_mut;
use log::info;
use mlibs::cmsis_rtos2::kernel::{os_delay, os_kernel_get_tick_count};
use mlibs::cmsis_rtos2::thread::Thread;
use mlibs::cmsis_rtos2::thread::{PRIORITY_HIGH1, THREAD_DETACHED};
use rtt_target::rprintln;


use crate::adc;
use crate::driver::{led, uart};

static mut APP_TASK: Thread<2048, PRIORITY_HIGH1, THREAD_DETACHED> = Thread::default();
static mut RECV_TASK: Thread<1024, PRIORITY_HIGH1, THREAD_DETACHED> = Thread::default();

pub unsafe fn app_task_start() {
    APP_TASK.unsafe_new("app_task", app_task, null_mut());
}


extern "C" fn app_task(_: *mut c_void) {
    led::init();
    uart::init();
    adc::init();
    uart::write(b"Hello\r\n");
    unsafe { RECV_TASK.unsafe_new("recv", recv_task, null_mut()); }
    loop {
        led::led_toggle();
        info!("adc:({}, {})", adc::in3(), adc::in4());
        os_delay(500);
    }
}

extern "C" fn recv_task(_: *mut c_void) {
    info!("recv run");

    loop {
        let buf = uart::recv();
        uart::write(buf);
    }
}


